# gozerlib/persist/mempersist.py
#
#

"""
    allow data to be written to memcache in JSON format. creating the persisted 
    object restores data. 

"""

## gozerlib imports

from gozerlib.utils.trace import calledfrom

## simplejson imports

from waveapi.simplejson import load, dump, loads, dumps

## google imports

from google.appengine.api.memcache import get, set, replace

# basic imports
import pickle
import thread
import os
import copy
import sys
import logging

class MPersist(object):

    """ 
        persist data to memcached backed JSON. 

        :param filename: filename to store data in
        :type filename: string
        :param default: default data in case not initialised

    """

    def __init__(self, filename, default={}, init=True):
        self.fn = unicode(filename) # filename to save to
        try:
            jsontxt = get(self.fn)
        except:
            jsontxt = str(default)
        if not jsontxt:
            jsontxt = str(default)
        self.data = loads(jsontxt)
        logging.debug('mem loaded %s (%s)' % (self.fn, len(jsontxt)))

    def save(self):

        """ save json data to database. """

        jsondata = dumps(self.data)
        replace(self.fn, jsondata)
        logging.debug('mem saved %s (%s)' % (self.fn, len(jsondata)))

class MPlugPersist(MPersist):

    """ 
        persist plug related data. 
        data is stored in gozerstore/plugs/{plugin}/{filename}

        :param filename: filename to store data in
        :type filename: string
        :param default: default data in case not initialised

    """

    def __init__(self, filename, default=None):

        # retrieve plugname where object is constructed
        plugname = calledfrom(sys._getframe())

        # call base constructor with appropiate filename
        Persist.__init__(self, 'gozerstore' + os.sep + 'plugs' + os.sep + plugname + os.sep + filename)

